package com.bjsxt.shop.goods.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bjsxt.shop.common.util.ConstatFinalUtil;
import com.bjsxt.shop.common.util.HttpUtil;
import com.bjsxt.shop.common.util.JdSpliderUtil;
import com.bjsxt.shop.common.util.PageInfoUtil;
import com.bjsxt.shop.goods.pojo.AGoods;
import com.bjsxt.shop.goods.service.IGoodsService;
import com.bjsxt.shop.goods.service.ISpliderDataService;
import com.bjsxt.shop.goods.util.MyThreadUtil;

/**
 * 采集数据
 * @author WangshSxt
 *
 */
@Service("spliderDataService")
public class SpliderDataServiceImpl implements ISpliderDataService
{
	@Resource
	private IGoodsService goodsService ; 
	
	public void saveBatchGoodsService(String cate)
	{
		/* 抓取京东的列表数据
		 * 写分页
		 *  */
		JdSpliderUtil jdSpliderUtil = new JdSpliderUtil() ; 
		JSONObject resultJSON = jdSpliderUtil.list("");
		/* 取到总页数 */
		JSONObject dataJSON = (JSONObject) resultJSON.get("data");
		/*int totalPage = Integer.valueOf(dataJSON.get("totalPage") + "");*/
		/*
		 * 总共有14页数据,
		 * 五个线程跑
		 * 每个线程执行页码如下:
		 * 
		 * 每一个线程:1--3
		 * 每二个个线程:4--6
		 * 每三个个线程:7--9
		 * 每四个个线程:10--12
		 * 每五个个线程:13--14
		 * */
		int totalPage = 14;
		int threadCount = 3 ; 
		/* 每个线程执行多少页 */
		/* 像分页,获取总页数 
		 * 和计算总页数的方法一致
		 * */
		PageInfoUtil pageInfoUtil = new PageInfoUtil() ; 
		pageInfoUtil.setTotalRecord(totalPage);
		pageInfoUtil.setPageSize(threadCount);
		
		/*
		 * 应该执行的线程数量
		 * */
		List myThreadList = new ArrayList();
		for(int i = 1 ; i <= 5 ; i ++)
		{
			pageInfoUtil.setCurrentPage(i);
			/* 每一个线程
			 * 执行的页数(数据) */
			String stPage = pageInfoUtil.getCurrRecord() + 1 + "" ; 
			int edPage = pageInfoUtil.getCurrRecord() + pageInfoUtil.getPageSize() ; 
			if(edPage > totalPage )
			{
				edPage = totalPage ; 
			}
			String edPageStr = edPage + "" ; 
			System.out.println(stPage+ "-----" + edPageStr);
			/*saveBatchPerPage(i);*/
			
			/* 线程里面要做的事情
			 * 采集数据页码,从(pageInfoUtil.getCurrRecord() + 1) + pageInfoUtil.getPageSize() ; 
			 * 应该做一个循环
			 *  */
			MyThreadUtil myThreadUtil = new MyThreadUtil() ; 
			Map<String, Object> paramsMap = new HashMap<String, Object>();
			paramsMap.put("stPage", stPage);
			paramsMap.put("edPage", edPageStr);
			/* 赋值 */
			myThreadUtil.setParamsMap(paramsMap);
			myThreadUtil.setSpliderDataService(this);
			myThreadList.add(myThreadUtil);
		}
		
		/* 主流程等待 */
		ExecutorService executorService = Executors.newFixedThreadPool(myThreadList.size());
		try
		{
			executorService.invokeAll(myThreadList);
		} catch (InterruptedException e)
		{
			e.printStackTrace();
		}finally
		{
			executorService.shutdown();
		}
	}
	
	/**
	 * 处理每一页的数据
	 * @param jdSpliderUtil
	 * @param i
	 */
	public void saveBatchPerPage(int i)
	{
		JdSpliderUtil jdSpliderUtil = new JdSpliderUtil() ; 
		JSONObject resultJSON = new JSONObject();
		JSONObject dataJSON = new JSONObject();
		/* 传第几页 */
		resultJSON = jdSpliderUtil.list(i + "");
		
		dataJSON = (JSONObject) resultJSON.get("data");
		/* 取到商品 */
		JSONArray goodsArr = (JSONArray) dataJSON.get("goodsList");
		for (Iterator iterator = goodsArr.iterator(); iterator.hasNext();)
		{
			JSONObject goodsTemp = (JSONObject) iterator.next();
			/* 入库 */
			AGoods goods = new AGoods() ;
			/* 0:采集 */
			goods.setAdminsId(0);
			/* 根据传入的分类标识,去分类表查询,取到Id */
			goods.setCateId(5);
			/* 建议将京东的id也存储起来 */
			goods.setUrl(UUID.randomUUID().toString());
			goods.setName(goodsTemp.getString("name"));
			goods.setTitle(goodsTemp.getString("name"));
			goods.setListImgPath("http:" + goodsTemp.getString("imgPath"));
			goods.setPrice(goodsTemp.getDoubleValue("price"));
			goods.setMarketPrice(goodsTemp.getDoubleValue("price"));
			goods.setContent("");
			
			goods.setCreateTime(new Date());
			goods.setUpdateTime(new Date());
			goods.setPubTime(new Date());
			JSONObject resDbJSON = this.goodsService.saveOneGoodsService(goods);
		}
	}

	@Override
	public Map<String, Object> findCondListGoodsService(PageInfoUtil pageInfoUtil, Map<String, Object> condMap)
	{
		/* 存储结果 */
		Map<String, Object> resultMap = new HashMap<String, Object>();
		/* 请求solr的服务 */
		HttpUtil httpUtil = new HttpUtil() ; 
		
		/**
		 * http://localhost:8983/solr/test/select?indent=on&q=%E5%B0%8F%E7%B1%B3&wt=json
		 */
		Map<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("indent", "on");
		paramsMap.put("q", "name:" + condMap.get("keyword"));
		paramsMap.put("wt", "json");
		paramsMap.put("start", pageInfoUtil.getCurrRecord() + "");
		paramsMap.put("rows", pageInfoUtil.getPageSize() + "");
		String result = httpUtil.methodPost(ConstatFinalUtil.CONFIG_JSON.getString("solr.search.url"), paramsMap);
		/*ConstatFinalUtil.SYS_LOGGER.info("-------返回结果:{}------",result);*/
		
		/*如何将字符串转换成JSON对象呢?  */
		JSONObject resultJSON = (JSONObject) JSON.parse(result);
		/* 获取到总记录数和List数据 */
		JSONObject responseJSON = (JSONObject) resultJSON.get("response");
		/* 取得总记录数 */
		String totalRecord = responseJSON.get("numFound") + "";
		/* 取得商品列表 */
		JSONArray goodsArr = (JSONArray) responseJSON.get("docs");
		
		List<AGoods> goodsList = new ArrayList<AGoods>();
		for (Iterator iterator = goodsArr.iterator(); iterator.hasNext();)
		{
			JSONObject goodsJSON = (JSONObject) iterator.next();
			/*
			 * 将json变成商品对象
			 * */
			AGoods goods = new AGoods() ; 
			goods = goods.parseJSON(goodsJSON);
			goodsList.add(goods);
		}
		
		resultMap.put("totalRecord", totalRecord);
		resultMap.put("list", goodsList);
		return resultMap;
	}

}
